package com.yitiao.consumer;


import com.yitiao.annotation.MessageHandlerSign;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.annotation.AnnotationUtils;

import java.util.HashMap;
import java.util.Map;

@Configuration
@ComponentScan(basePackages = "com.yitiao.*",
        includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, value = {MessageHandlerSign.class}),
        useDefaultFilters = false)
public class MessageHandlerConfig {

    @Bean("messageHandlerMap")
    public Map<String, MessageHandler> messageHandlerMap(ApplicationContext context) {
        Map<String, MessageHandler> map = new HashMap<>();
        Map<String, Object> beans = context.getBeansWithAnnotation(MessageHandlerSign.class);
        for (Object bean : beans.values()) {
            if (bean instanceof MessageHandler) {
                MessageHandlerSign annotation = AnnotationUtils.findAnnotation(bean.getClass(), MessageHandlerSign.class);
                String name = (String) AnnotationUtils.getValue(annotation, "name");
                map.put(name, (MessageHandler) bean);
            }
        }
        return map;
    }
}
